const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { Notice } = require("@models/notice");
const { where } = require("sequelize");

const router = new Router({
  prefix: "/admin/notice",
});

// 添加公告
router.post("/add", new Auth(16).m, async (ctx, next) => {
  const { content } = ctx.request.body;
  const notice = await Notice.create({ content });
  if (!notice) {
    throw new global.errs.AuthFailed("添加失败");
  }
  ctx.body = {
    code: 200,
    msg: "添加成功",
    data: {},
  };
});
// 发布公告
router.post("/publish", new Auth(16).m, async (ctx, next) => {
  const { notice_id, is_on } = ctx.request.body;
  if (is_on) {
    await Notice.update({ is_on: false }, { where: {} });
  }

  const notice = await Notice.update(
    { is_on },
    {
      where: { notice_id },
    }
  );
  if (!notice) {
    throw new global.errs.AuthFailed("发布失败");
  }
  ctx.body = {
    code: 200,
    msg: is_on ? "发布成功" : "取消发布成功",
    data: {},
  };
});

// 获取公告列表
router.post("/list", new Auth(16).m, async (ctx, next) => {
  const { page = 1, pageSize = 20 } = ctx.query;
  const offset = (page - 1) * pageSize;
  const where = {};
  const { count: total, rows } = await Notice.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 更新公告
router.post("/update", new Auth(16).m, async (ctx, next) => {
  const { notice_id, content } = ctx.request.body;
  const notice = await Notice.update({ content }, { where: { notice_id } });
  if (!notice) {
    throw new global.errs.AuthFailed("公告不存在");
  }

  ctx.body = {
    code: 200,
    msg: "更新成功",
    data: {},
  };
});
// 删除公告
router.post("/delete", new Auth(16).m, async (ctx, next) => {
  const { notice_id } = ctx.request.body;
  const notice = await Notice.destroy({ where: { notice_id }, focus: true });
  if (!notice) {
    throw new global.errs.AuthFailed("公告不存在");
  }
  ctx.body = {
    code: 200,
    msg: "删除成功",
    data: {},
  };
});
module.exports = router;
